/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.simple;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.BeginRequestMessage;
import cn.easyplatform.messages.vos.AbstractPageVo;
import cn.easyplatform.messages.vos.TaskVo;
import cn.easyplatform.spi.service.TaskService;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.ext.ComponentBuilder;
import cn.easyplatform.web.ext.Destroyable;
import cn.easyplatform.web.ext.Widget;
import cn.easyplatform.web.ext.zul.Taskbox;
import cn.easyplatform.web.layout.IMainTaskBuilder;
import cn.easyplatform.web.layout.LayoutManagerFactory;
import cn.easyplatform.web.service.ServiceLocator;
import cn.easyplatform.web.task.BackendException;
import cn.easyplatform.web.task.MainTaskSupport;
import cn.easyplatform.web.task.OperableHandler;
import cn.easyplatform.web.task.support.ManagedComponent;
import cn.easyplatform.web.utils.TaskInfo;
import cn.easyplatform.web.utils.WebUtils;
import org.zkoss.zk.ui.Component;

import java.util.Iterator;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class TaskboxBuilder implements ComponentBuilder, Widget, Destroyable {

    private Taskbox task;

    private OperableHandler mainTaskHandler;

    //private FxPanelBuilder fxPanelBuilder;


    public TaskboxBuilder(OperableHandler main, Taskbox task) {
        this.mainTaskHandler = main;
        this.task = task;
    }

    @Override
    public Component build() {
        if (Strings.isBlank(task.getId()))
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<task>", "id");
        task.setAttribute("$proxy", this);
        if (task.isImmediate() && !Strings.isBlank(task.getEntity()))
            redraw();
        return task;
    }

    private void redraw() {
        TaskVo tv = new TaskVo(task.getEntity());
        tv.setOpenModel(Constants.OPEN_EMBBED);
        tv.setCid(task.getId());
        tv.setFrom(task.getFrom());
        if (!Strings.isBlank(task.getProcessCode()))
            tv.setProcessCode(task.getProcessCode());
        TaskService mtc = ServiceLocator
                .lookup(TaskService.class);
        BeginRequestMessage req = new BeginRequestMessage(tv);
        req.setId(mainTaskHandler.getId());
        IResponseMessage<?> resp = mtc.begin(req);
        if (resp.isSuccess()) {
            if (resp.getBody() != null
                    && resp.getBody() instanceof AbstractPageVo) {
                MainTaskSupport builder = null;
                try {
                    AbstractPageVo pv = (AbstractPageVo) resp.getBody();
                    builder = (MainTaskSupport) LayoutManagerFactory
                            .createLayoutManager()
                            .getMainTaskBuilder(task,
                                    tv.getId(), pv);
                    ((IMainTaskBuilder) builder).build();
                    MainTaskSupport ts = null;
                    if (mainTaskHandler instanceof MainTaskSupport)
                        ts = (MainTaskSupport) mainTaskHandler;
                    else
                        ts = (MainTaskSupport) mainTaskHandler.getParent();
                    ts.appendChild(task.getId(), builder);
                    Iterator<ManagedComponent> itr = ts
                            .getManagedEntityComponents().iterator();
                    while (itr.hasNext()) {
                        ManagedComponent es = itr.next();
                        if (es.getComponent() == this.task) {
                            itr.remove();
                            break;
                        }
                    }
                    TaskInfo taskInfo = new TaskInfo(task.getEntity());
                    taskInfo.setId(pv.getId());
                    taskInfo.setTitle(pv.getTitile());
                    taskInfo.setImage(pv.getImage());
                    taskInfo.setParentId(mainTaskHandler.getId());
                    WebUtils.registryTask(taskInfo);
                    WebUtils.setAnonymousInfo(task.getDesktop(), pv.getId());
                } catch (EasyPlatformWithLabelKeyException ex) {
                    builder.close(false);
                    throw ex;
                } catch (BackendException ex) {
                    builder.close(false);
                    throw ex;
                } catch (Exception ex) {
                    builder.close(false);
                    throw Lang.wrapThrow(ex);
                }
            }
        } else
            throw new BackendException(resp);
    }

    @Override
    public void reload(Component c) {
        if (Strings.isBlank(task.getEntity()))
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<taskbox>", "entity");
        redraw();
    }

    /**
     * 创建金融面板
     */
//    private void buildPanel(String zul, Destination rfqTopic, Destination upQueue, Destination downQueue) {
//        Executions.createComponentsDirectly(zul, "zul", task, null);
//        fxPanelBuilder = AbstractFxPanelBuilder.createInstance(task.getFxType(), mainTaskHandler, rfqTopic, upQueue, downQueue);
//        fxPanelBuilder.build(task);
//    }

    /**
     * 销毁相关Queue资源
     */
    @Override
    public void destory() {
//        if (fxPanelBuilder != null)
//            fxPanelBuilder.destory();
        if (task.getFirstChild() != null)
            task.getFirstChild().detach();
    }
}
